package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-admin-server/app/dao/model"
	"go-admin-server/app/dto"
	"go-admin-server/app/dto/response"
	"go-admin-server/app/service"
	"go-admin-server/common/auth"
	"go-admin-server/common/base"
	"net/http"
)

type loginApi struct{}

func NewLoginHttp(group *gin.RouterGroup) {
	s := &loginApi{}
	group.POST("/auth/login", s.Login)
	group.POST("/auth/register", s.Register)
	group.GET("/auth/logout", s.Logout)
	group.GET("/login/UpdatePassword", s.UpdatePassword)
}

func (a *loginApi) Login(c *gin.Context) {
	user := new(model.User)
	if err := c.BindJSON(user); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	user, err := service.LoginService.Auth(user)
	if err != nil {
		response.Fail(c, http.StatusUnauthorized, err.Error())
		return
	}

	userInfo := &auth.UserInfo{
		Id:       user.ID,
		UserName: user.UserName,
		Email:    user.Email,
	}

	token, err := auth.GenerateToken(userInfo)
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
		return
	}

	c.SetCookie(base.CookieTokenName, token, 3600*24, "/", "", true, true)
	c.SetCookie(base.CookieLoginUser, user.UserName, 3600*24, "/", "", true, false)

	response.Success(c, dto.LoginInfo{
		UserID:   user.ID,
		UserName: user.UserName,
		RealName: user.RealName,
		//Roles:[],
		Token: token,
	})
}

func (a *loginApi) Register(c *gin.Context) {
	user := new(model.User)
	if err := c.BindJSON(user); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	if err := service.UserService.Validate(user); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	err := service.UserService.Create(user)
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}
	response.Success(c, user)
}

func (a *loginApi) Logout(c *gin.Context) {
	c.SetCookie(base.CookieTokenName, "", -1, "/", "", true, true)
	c.SetCookie(base.CookieLoginUser, "", -1, "/", "", true, false)
	response.Success(c, nil)
}

func (a *loginApi) UpdatePassword(c *gin.Context) {
	//var item dto.UpdatePasswordParam
	//if err := ginx.ParseJSON(c, &item); err != nil {
	//	response.Error(c, err)
	//	return
	//}
	//err := service.LoginService.UpdatePassword(c, contextx.FromUserID(ctx), item)
	//if err != nil {
	//	ginx.ResError(c, err)
	//	return
	//}
	response.Ok(c)
}

func (a *loginApi) GetLoginInfo(c *gin.Context) {
	info, err := service.LoginService.GetLoginInfo(1)
	if err != nil {
		response.Error(c, err)
		return
	}
	response.Success(c, &info)
}

func (a *loginApi) formatTokenUserID(userID uint64, userName string) string {
	return fmt.Sprintf("%d-%s", userID, userName)
}
